﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CYTS.Aoyou.Framework.Cache;
using CYTS.Aoyou.Framework.CAInterface;

namespace CYTS.Aoyou.Framework.CacheAccess
{
    /// <summary>
    /// Session备用缓存适配器
    /// </summary>
    public class SessionBackupCacheAdapterForAppFabric : CacheAdapterBase, ISessionBackupCacheAdapter, ICacheAdapter
    {
        public SessionBackupCacheAdapterForAppFabric(CacheProvider provider)
            : base(provider)
        { }

        public void Set<T>(string key, T value, TimeSpan expireTime)
        {
            List<CacheConnection> connectionList = null;
            if (!this.DicCacheConnection.TryGetValue("SessionCache", out connectionList))
            {
                throw new Exception("未找到对应的缓存连接串");
            } 
            
            AppFabricHelper helper = new AppFabricHelper(connectionList.Select(p => p.Host + ":" + p.Port).ToArray());
            helper.Put(key, value, this.Region, expireTime);
        }

        public T Get<T>(string key)
        {
            List<CacheConnection> connectionList = null;
            if (!this.DicCacheConnection.TryGetValue("SessionCache", out connectionList))
            {
                throw new Exception("未找到对应的缓存连接串");
            } 
            
            AppFabricHelper helper = new AppFabricHelper(connectionList.Select(p => p.Host + ":" + p.Port).ToArray());
            return (T)helper.Get(key, this.Region);
        }


        public void Remove(string key)
        {
            List<CacheConnection> connectionList = null;
            if (!this.DicCacheConnection.TryGetValue("SessionCache", out connectionList))
            {
                throw new Exception("未找到对应的缓存连接串");
            }

            AppFabricHelper helper = new AppFabricHelper(connectionList.Select(p => p.Host + ":" + p.Port).ToArray());
            helper.Delete(key, this.Region);
        }
    }
}
